package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @projectName: hm-dianping
 * @package: com.hmdp.utils
 * @className: SimpleRedisLock
 * @author: Mocrash
 * @description: TODO
 * @date: 2024/9/6 13:58
 * @version: 1.0
 */
public class SimpleRedisLock implements ILock {
    private StringRedisTemplate stringRedisTemplate;
    private String key;

    private static final String ID_PREFIX = UUID.fastUUID().toString(true) + "-";
    private static final String KEY_PREFIX = "lock:";

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.key = KEY_PREFIX + name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程id作为线程标识
        String flag = ID_PREFIX + Thread.currentThread().getId();
        //获取锁
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(key, flag, timeoutSec, TimeUnit.SECONDS));
    }

    @Override
    public void unLock() {
        //使用lua脚本来解锁保证原子性
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(key),
                ID_PREFIX + Thread.currentThread().getId()
        );
    }

    /*@Override
    public void unLock() {
        String currentFlag = ID_PREFIX + Thread.currentThread().getId();
        String redisFlag = stringRedisTemplate.opsForValue().get(key);
        if (redisFlag == null || !redisFlag.equals(currentFlag)){
            return;
        }
        stringRedisTemplate.delete(key);
    }*/
}
